package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.DishExistException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     * @param dishDTO
     */
    @Transactional
    @Override
    public void create(DishDTO dishDTO) {
        //判断菜品名是否重复
        Integer dishNameCount = dishMapper.selectNameCount(dishDTO.getName());
        if(dishNameCount>0){
            throw new DishExistException(MessageConstant.REPEAT_DISH_NAME);
        }
        //新增菜品表
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dish.setStatus(StatusConstant.DISABLE);
        //主键回显
        dishMapper.insert(dish);
        //新增口味表
        List<DishFlavor> flavors = dishDTO.getFlavors();
        createBatchDishFlavor(flavors, dish);
    }


    /**
     * 分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        //1.开启分页
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        //2.原始查询 --- 通过传一个实体类来查询
        Dish dishQuery = new Dish();
        BeanUtils.copyProperties(dishPageQueryDTO,dishQuery);
        List<Dish> dishList = dishMapper.selectList(dishQuery);
        //3.类型转换
        PageInfo<Dish> pageInfo = new PageInfo<>(dishList);
        //4.结果封装
        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
    }

    /**
     * 批量删除
     * @param ids
     */
    @Override
    @Transactional
    public void delete(List<Long> ids) {
        //1.todo 起售不能删除
        Integer countByIdsAndStatus = dishMapper.selectByIdsAndStatus(ids,StatusConstant.ENABLE);
        if (countByIdsAndStatus>0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //2.todo 被套餐关联不能删除
        Integer countByIds = setmealDishMapper.selectByIds(ids);
        if(countByIds > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //3.批量删除
        dishMapper.delete(ids);
        //4.口味表批量删除
        dishFlavorMapper.delete(ids);
    }

    /**
     * 回显
     * @param id
     * @return
     */
    @Override
    public DishVO queryById(Long id) {
        //1.查询菜品的详情信息
        Dish dish = dishMapper.selectById(id);
        //2.查询口味的列表信息
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectListByDishId(id);
        //3.封装数据
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /**
     * 根据id修改菜品
     * @param dishDTO
     */
    @Transactional
    @Override
    public void update(DishDTO dishDTO) {
        //1.修改dish表
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);
        //2.修改口味表
        //2.1先删除
        dishFlavorMapper.delete(Collections.singletonList(dishDTO.getId()));
        //2.2后添加口味表
        List<DishFlavor> flavors = dishDTO.getFlavors();
        createBatchDishFlavor(flavors,dish);
    }

    /**
     * 菜品起售、停售
     *
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(Long id, Integer status) {
        Dish dish = dishMapper.selectById(id);
        dish.setStatus(status);
        dishMapper.update(dish);
    }

    /**
     * 根据分类id查询菜品和口味
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> list(Long categoryId) {
        /*String cacheKey = "DISH_"+categoryId;
        String vos = (String)redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.hasText(vos)){
            return JSON.parseArray(vos,DishVO.class);
        }*/

        List<Dish> dishList = dishMapper.selectByCategoryId(categoryId);
        List<DishVO> dishVOList = new ArrayList<>();
        dishList.forEach(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish,dishVO);
            List<DishFlavor> dishFlavors = dishFlavorMapper.selectListByDishId(dishVO.getId());
            dishVO.setFlavors(dishFlavors);
            dishVOList.add(dishVO);
        });

        //redisTemplate.opsForValue().set(cacheKey,dishVOList);
        return dishVOList;
    }




    /**
     * 根据dishID批量新增口味信息
     * @param flavors
     * @param dish
     */
    private void createBatchDishFlavor(List<DishFlavor> flavors, Dish dish) {
        //List<DishFlavor> flavors = dishDTO.getFlavors();
        if (!CollectionUtils.isEmpty(flavors)){
            flavors.forEach(dishFlavor->{
                dishFlavor.setDishId(dish.getId());
            });
        }
        dishFlavorMapper.insertBatch(flavors);
    }



}
